import { createRouter, createWebHashHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import(/* webpackChunkName: "home" */'../views/home/Home')
  }, {
    path: '/shop/:id',
    name: 'Shop',
    component: () => import(/* webpackChunkName: "shop" */'../views/shop/Shop')
  }, {
    path: '/cart',
    name: 'Cart',
    component: () => import(/* webpackChunkName: "cart" */'../views/cartPage/CartPage')
  },
  {
    path: '/orderList',
    name: 'OrderList',
    component: () => import(/* webpackChunkName: "orderList" */'../views/orderList/OrderList')
  },
  {
    path: '/user',
    name: 'User',
    component: () => import(/* webpackChunkName: "user" */'../views/user/User')
  },
  {
    path: '/address',
    name: 'Address',
    component: () => import(/* webpackChunkName: "address" */'../views/address/Address'),
    beforeEnter(to, form, next) {
      form.name === 'Order' ? next() : next('/');
    }
  },
  {
    path: '/myAddress',
    name: 'myAddress',
    component: () => import(/* webpackChunkName: "myAddress" */'../views/myAddress/MyAddress')
  },
  {
    path: '/search',
    name: 'search',
    component: () => import(/* webpackChunkName: "search" */'../views/search/Search')
  },
  {
    path: '/searchList',
    name: 'searchList',
    component: () => import(/* webpackChunkName: "searchList" */'../views/searchList/SearchList')
  },
  {
    path: '/addressInfo/:id',
    name: 'addressInfo',
    component: () => import(/* webpackChunkName: "addressInfo" */'../views/myAddress/AddressInfo')
  },
  {
    path: '/setAddress',
    name: 'setAddress',
    component: () => import(/* webpackChunkName: "setAddress" */'../views/myAddress/SetAddress')
  },
  {
    path: '/orderConfirmation/:id',
    name: 'Order',
    component: () => import(/* webpackChunkName: "order" */'../views/orderConfirmation/OrderConfirmation')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => { return import(/* webpackChunkName: "login" */'../views/Login/Login') },
    beforeEnter(to, from, next) {
      const { isLogin } = localStorage;
      isLogin ? next('/') : next();
    }
  }, {
    path: '/register',
    name: 'Register',
    component: () => { return import(/* webpackChunkName: "Register" */'../views/register/Register') },
    beforeEnter(to, from, next) {
      const { isLogin } = localStorage;
      isLogin ? next('/') : next();
    }
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
router.beforeEach((to, form, next) => {
  const { isLogin } = localStorage;
  (isLogin || to.name === 'Login' || to.name === 'Register') ? next() : next('/login');
})
export default router
